package com.web.exiaodao.business.controller;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Shop;
import com.web.exiaodao.business.service.CategoryService;
import com.web.exiaodao.business.service.ShopService;
import com.web.exiaodao.remote.vo.ShopStandardNameVo;
import com.web.exiaodao.remote.vo.ShopStandardValuesVo;
import com.web.exiaodao.remote.vo.ShopVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author eason.zt
 * @version V1.0
 * @Title: ShopController.java
 * @Package com.web.webstart.business.controller
 * @Description: 商品表控制器
 * @date 2016-11-02 17:35:34
 */
@Controller
@RequestMapping("/cms/shop")
public class ShopController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ShopController.class);

    @Autowired
    private ShopService shopService;
    @Autowired
    private CategoryService categoryService;

    /**
     * @param pageSize
     * @param status     //默认查询非删除3的数据,具体类型参照XaConstant.Status
     *                   @param sortData
     * @param jsonFilter
     * @return
     * @Title: findShopNEStatusPage
     * @Description: 分页查询Shop     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findShopNEStatusPage", method = RequestMethod.POST)
    public XaResult<Page<ShopVo>> findShopNEStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "3") Integer status,
            @RequestParam(defaultValue = "[{property:'sort',direction:'ASC'},{property:'clickCont',direction:'DESC'},{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<ShopVo>> xr = new XaResult<>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
        return shopService.findListNEStatusByFilter(status, filterParams, pageable);
    }

    /**
     * @param pageSize
     * @param status     //默认查询正常状态1的数据,具体类型参照XaConstant.Status
     *                   @param sortData
     * @param jsonFilter
     * @return
     * @Title: findShopEQStatusPage
     * @Description: (预留)分页查询Shop     * @param nextPage
     */
    @ResponseBody
    @RequestMapping(value = "findShopEQStatusPage", method = RequestMethod.POST)
    public XaResult<Page<ShopVo>> findShopEQStatusPage(
            @RequestParam(defaultValue = "0") Integer nextPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
            @RequestParam(defaultValue = "{}") String jsonFilter
    ) throws BusinessException {
        XaResult<Page<ShopVo>> xr = new XaResult<Page<ShopVo>>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith(jsonFilter, "search_");
        return shopService.findListEQStatusByFilter(status, filterParams, pageable);
    }

    /**
     * @param modelId
     * @return
     * @Title: findShopById
     * @Description: 根据ID查找单条实体
     */
    @ResponseBody
    @RequestMapping(value = "findShopById", method = RequestMethod.POST)
    public XaResult<ShopVo> findShopById(
            @RequestParam Long modelId
    ) throws BusinessException {
        XaResult<ShopVo> xr = new XaResult<ShopVo>();
        return shopService.findShopById(modelId);
    }

    /**
     * /**
     *
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "新增Or商品", notes = "供前端前期填充数据测试使用,上线后删除;新增商品表,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveShop", method = RequestMethod.POST)
    public XaResult<ShopVo> saveShop(
            @ApiParam("商品id,字段名:shopId") @RequestParam(value = "shopId", required = false) String shopId,
            @ApiParam("商品名称,字段名:shopProductName") @RequestParam(value = "shopProductName") String shopProductName,
            @ApiParam("商品原价,字段名:originalPrice") @RequestParam(value = "originalPrice") String originalPrice,
            @ApiParam("商品优惠价格,字段名:shopProductPrice") @RequestParam(value = "shopProductPrice") String shopProductPrice,
            @ApiParam("商品简介（产品参数）,字段名:shopProductBrief") @RequestParam(value = "shopProductBrief") String shopProductBrief,
            @ApiParam("抵扣比例,字段名:折扣比例") @RequestParam(value = "discountRate", required = false, defaultValue = Shop.DISCOUNT_RATE_DEFAULT + "") Double discountRate,
            @ApiParam("商品图片（banner）URL，多张逗号分割,字段名:shopProductPicUrls") @RequestParam(value = "shopProductPicUrls") String shopProductPicUrls,
            @ApiParam("商品介绍-图文详情-富文本,字段名:shopProductIntroduce") @RequestParam(value = "shopProductIntroduce") String shopProductIntroduce,
            @ApiParam("商品分类,字段名:categoryType") @RequestParam(value = "categoryType") String categoryType,
            @ApiParam("商品规格,字段名:standards,格式\"颜色:红色,蓝色,灰色,白色;尺寸:大号,中号,小号\"") @RequestParam(value = "standards") String standards,
            @ApiParam("库存,字段名:shopProductInventory") @RequestParam(value = "shopProductInventory") String shopProductInventory,
            @ApiParam("品牌,字段名:brand,eg:e孝道官网,苏宁,苏泊尔") @RequestParam(value = "brand") String brand,
            @ApiParam("排序值;排序值") @RequestParam(value = "sort", defaultValue = Shop.SORT_DEFAULT +"") Long sort,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<ShopVo> xr = new XaResult<ShopVo>();
        if (XaUtil.isEmpty(shopProductName)) {
            xr.error("商品名字不能为空!");
            return xr;
        }
        if (shopProductName.length() > 50) {
            xr.error("商品名字不能超过50个字符!");
            return xr;
        }
        if (Long.parseLong(categoryType) < 0) {
            xr.error("商品分类不能小于0!");
            return xr;
        }
        if (XaUtil.isEmpty(standards)) {
            xr.error("商品必须要有规格!");
            return xr;
        }
        if (Double.parseDouble(originalPrice) < 0) {
            xr.error("商品原价错误小于0!");
            return xr;
        }
        if (Double.parseDouble(shopProductPrice) < 0) {
            xr.error("商品价格错误小于0!");
            return xr;
        }
        if (Double.parseDouble(shopProductPrice) > Double.parseDouble(originalPrice)) {
            xr.error("优化价格不能大于原价!");
            return xr;
        }
        if ( discountRate != null ) {
            if (discountRate < 0 || discountRate > 1) {
                xr.error("折扣比例只能为[0,0.99]");
                return xr;
            }
        }
        categoryService.findOne(Long.parseLong(categoryType));

        Shop model = new Shop();
        model.setId(XaUtil.isEmpty(shopId) ? null : Long.parseLong(shopId));
        model.setShopProductName(shopProductName);
        model.setOriginalPrice(originalPrice);
        model.setShopProductPrice(shopProductPrice);
        model.setDiscountRate(discountRate);
        model.setShopProductBrief(shopProductBrief);
        model.setShopProductPicUrls(shopProductPicUrls);
        model.setShopProductIntroduce(shopProductIntroduce);
        model.setCategoryType(Long.parseLong(categoryType));
        model.setShopProductInventory(Long.parseLong(shopProductInventory));
        model.setBrand(brand);
        model.setSort(sort);

        //拆分规格
        List<ShopStandardNameVo> shopStandards = new ArrayList<>();
        if (XaUtil.isNotEmpty(standards)) {
            //颜色:红色,蓝色,灰色,白色;尺寸:大号,中号,小号
            standards = standards.replace(JConstant.SYMBOL_DOT_CN, JConstant.SYMBOL_DOT);      //，,
            standards = standards.replace(JConstant.SYMBOL_SEMICOLON_CN, JConstant.SYMBOL_SEMICOLON);//；;
            standards = standards.replace(JConstant.SYMBOL_COLON_CN, JConstant.SYMBOL_COLON);    //：:
            String[] specs = standards.split(JConstant.SYMBOL_SEMICOLON);//;
            if (standards.length() < 3 || XaUtil.isEmpty(specs[0]) || specs[0].length() < 3) {
                xr.error("商品规格错误,请检查!");
                return xr;
            }
            for (int i = 0; i < specs.length; i++) {
                String spec = specs[i];
                String[] sss = spec.split(JConstant.SYMBOL_COLON);//:
                if (sss.length != 2 || XaUtil.isEmpty(sss[0]) || XaUtil.isEmpty(sss[1])) {
                    xr.error("商品规格格式错误!");
                    return xr;
                }
                String shopStandName = sss[0];//颜色
                String shopStandsSpecs = sss[1];//红色,蓝色,灰色,白色
                String[] values = shopStandsSpecs.split(JConstant.SYMBOL_DOT);//,

                ShopStandardNameVo standard = new ShopStandardNameVo();
                standard.setShopStandsName(shopStandName);

                for (int j = 0; j < values.length; ++j) {
                    ShopStandardValuesVo valuesVo = new ShopStandardValuesVo();
                    valuesVo.setShopStandsValue(values[j]);
                    standard.getShopStandsValues().add(valuesVo);
                }
                shopStandards.add(standard);
            }
        }
        return shopService.createOrUpdateModelWithStandNames(model, shopStandards);
    }

    /**
     * @param modelIds 多个实体id,中间用逗号隔开
     * @param status   操作类型,status类型见XaConstant.Status,默认删除操作
     * @return
     * @Title: multiOperateShopByIds
     * @Description: 批量操作多个实体状态, 根据status进行操作
     */
    @ResponseBody
    @RequestMapping(value = "operateShopByIds", method = RequestMethod.POST)
    public XaResult<ShopVo> operateShopByIds(
            HttpServletRequest request,
            @RequestParam String modelIds,
            @RequestParam(defaultValue = "3") Integer status
    ) throws BusinessException {
        return shopService.multiOperate(modelIds, status);
    }


    /**
     * @return
     * @Title: findShopCountByCategoryType
     * @Description: 查询指定类别的商品数量
     */
    @ResponseBody
    @RequestMapping(value = "findShopCountByCategoryType", method = RequestMethod.POST)
    public XaResult<Long> findShopList(
            HttpServletRequest request,
            @RequestParam Long categoryType
    ) throws Exception {
        return shopService.findShopCountByCategoryType(categoryType);
    }



    /**
     * @param photoFile
     * @param request
     * @return
     * @Title: upload
     * @Description: 图片上传
     */
    @ResponseBody
    @RequestMapping(value = "photoUpload", method = RequestMethod.POST)
    public XaResult<String> photoUpload(
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
            HttpServletRequest request) {
        XaResult<String> xr = new XaResult<String>();
        LOGGER.info("shop 图片上传 photoUpload");
        String root = request.getSession().getServletContext().getRealPath("/");
        String picturePath = "/upload/shop";
        String ext = photoFile.getOriginalFilename().substring(
                photoFile.getOriginalFilename().lastIndexOf("."));
        String newName = new Date().getTime() + ext;
        File filedict = new File(root + picturePath);
        if (!filedict.exists()) {
            filedict.mkdir();
        }
        File targetFile = new File(root + picturePath + File.separator
                + newName);
        try {
            if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpg")
                    || org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpeg")
                    || org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".png")) {
                photoFile.transferTo(targetFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                //Map<String, Integer> map = new HashMap<String, Integer>();
                //map.put("pictureHeight", height);
                //map.put("pictureWidth", width);
                xr.setCode(1);
                xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
                        + newName + ":" + height + ":" + width);
            } else {
                xr.setCode(0);
                xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传jpg/png图片");
            }
        } catch (IllegalStateException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
        } catch (IOException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
        } catch (Exception e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
        }
        return xr;
    }
}

